﻿using AutoMapper;
using MediatR;
using MES.Bom.API.Application.Command.BOM命令;
using MES.Bom.Domain;
using MES.Bom.ErrorCode;
using MES.Bom.Infrastructure;

namespace MES.Bom.API.Application.CommandHandler.BOM命令处理
{
    /// <summary>
    /// BOM添加命令处理
    /// </summary>
    public class BomAddCommandHandler : IRequestHandler<BomAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Boms> bomRepository;
        private readonly IBaseRepository<BomMaterial> bmRepository;
        private readonly IBaseRepository<BomCrafts> bcRepository;
        private readonly ILogger<BomAddCommand> logger;
        private readonly IMapper mapper;
        public BomAddCommandHandler(IBaseRepository<Boms> bomRepository, IBaseRepository<BomMaterial> bmRepository = null, ILogger<BomAddCommand> logger = null, IMapper mapper = null, IBaseRepository<BomCrafts> bcRepository = null)
        {
            this.bomRepository = bomRepository;
            this.bmRepository = bmRepository;
            this.logger = logger;
            this.mapper = mapper;
            this.bcRepository = bcRepository;
        }

        public async Task<APIResult<int>> Handle(BomAddCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var model = mapper.Map<Boms>(request);
                var r = bomRepository.GetValues().Where(x => x.BomCode == request.BomCode).FirstOrDefault();
                if (r != null) 
                {
                    result.Code = APIEnums.Fail;
                    result.Message = "BOM编号已存在，请重新输入";
                    return Task.FromResult(result).Result;
                }
               
                using (var ts = await bomRepository._context.Database.BeginTransactionAsync()) 
                {
                    try
                    {
                        //添加BOM
                        await bomRepository.AddAsync(model);
                        int bomid = (bomRepository.GetValues().FirstOrDefault(x => x.BomCode == request.BomCode)).ID;
                        //添加BOM物料
                        List<BomMaterial> bomMaterials = request.Midlist
                          .Split(',')
                          .Select(pidStr =>
                          {
                              return new BomMaterial
                              {
                                  BomId = bomid,
                                  MaterialId = int.Parse(pidStr),
                              };
                          }).ToList();
                        await bmRepository.AddRangeAsync(bomMaterials);
                        //添加BOM工艺
                        List<BomCrafts> bomCrafts = request.Cidlist
                            .Split(",")
                            .Select(ids => 
                            {
                                return new BomCrafts
                                {
                                    CraftsId=int.Parse(ids),
                                    BomId=bomid,
                                };
                            }).ToList();
                        await bcRepository.AddRangeAsync(bomCrafts);
                        result.Code = APIEnums.Success;
                        result.Message = "添加成功";
                        result.Data = 1;
                        await ts.CommitAsync();
                    }
                    catch (Exception ex)
                    {
                        await ts.RollbackAsync();
                    }
                    return Task.FromResult(result).Result;
                }

            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
